package studio.xiaoyun.file.controller;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import studio.xiaoyun.core.Config;
import studio.xiaoyun.core.exception.InvalidParameterException;
import studio.xiaoyun.file.converter.FileConverter;
import studio.xiaoyun.web.ErrorCode;
import studio.xiaoyun.web.RestResult;
import studio.xiaoyun.web.WebException;
import studio.xiaoyun.web.dto.UploadFileDTO;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * 文件相关
 */
@Controller
@RequestMapping("/v1/file")
public class FileController {
    private Logger logger = LoggerFactory.getLogger(FileController.class);
    @Resource
    private FileRestController fileRestController;
    @Resource
    private FileConverter fileConverter;

    /**
     * 上传文件并预览文件
     * @param file 上传的文件
     */
    @RequestMapping(value = "/preview")
    public void uploadAndPreviewFile(HttpServletRequest request, HttpServletResponse response,MultipartFile file){
        RestResult restResult = fileRestController.uploadFile(file);
        @SuppressWarnings("rawtypes")
        UploadFileDTO resource = (UploadFileDTO) ((List) restResult.getModelMap().get(RestResult.KEY_ROWS)).get(0);
        request.setAttribute("title",resource.getOriginalFileName());
        previewFileByFilePath(request,response,resource.getUrl());
    }

    /**
     * 根据文件路径预览文件
     * @param filePath 相对于应用根目录的文件路径，例如: /tmp/file/abc.doc
     */
    @RequestMapping(value = "/previewFile")
    public void previewFileByFilePath(HttpServletRequest request, HttpServletResponse response,String filePath){
        logger.debug("预览文件,文件路径:"+filePath);
        if(StringUtils.isBlank(filePath)){
            throw new InvalidParameterException("filePath参数不能为空");
        }
        if(filePath.startsWith("/")){
            filePath = filePath.substring(1);
        }
        if(File.separator.equals("\\")){
            filePath = filePath.replaceAll("/","\\\\");
        }
        String fileName = Config.getBasePath()+filePath;
        //只允许预览临时目录中的文件
        if(!fileName.startsWith(Config.getUploadPath())){
            throw new WebException("无权限",ErrorCode.UNAUTHORIZED);
        }
        if(!new File(fileName).exists()){
            throw new InvalidParameterException("文件不存在");
        }
        String title = (String)request.getAttribute("title");
        if(title==null){
            title = "文件预览";
        }
        String htmlFileName = fileConverter.toHtml(fileName,title);  //将文件转换为html
        htmlFileName = htmlFileName.substring(Config.getBasePath().length());
        String path = request.getContextPath();
        String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
        String url = basePath+htmlFileName;
        try {
            response.sendRedirect(url);
        } catch (IOException e) {
            logger.error("跳转页面失败",e);
            throw new WebException("跳转页面失败,页面地址:"+url,e);
        }
    }

}
